package com.example.administrator.testdagger.tview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * com.example.administrator.testdagger.tview
 * (c)2018 AIR Times Inc. All rights reserved.
 *
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/7/27 9:23
 * @see com.example.administrator.testdagger.tview
 */
public class CustomDrawText extends View {
    public CustomDrawText(Context context) {
        this(context, null);
    }

    public CustomDrawText(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomDrawText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    Paint mPaint;
    Paint mTextPaint;
    Rect mRect;
    String mText = "nihaoa";

    private void init() {
        mPaint = new Paint();
        mTextPaint = new Paint();
        mRect = new Rect();

        mPaint.setColor(Color.GRAY);
        mTextPaint.setColor(Color.RED);
        mPaint.setAntiAlias(true);
        mTextPaint.setAntiAlias(true);

        mTextPaint.setTextSize(20);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();

        canvas.drawRect(0, 0, width, height, mPaint);
        mTextPaint.getTextBounds(mText, 0, mText.length(), mRect);

        int textWidth = mRect.width();
        int textHeight = mRect.height();

        canvas.drawText(mText, width / 2 - textWidth / 2, height / 2 - textHeight / 2, mTextPaint);
    }
}
